package main

import (
	"bufio"
	"flag"
	"fmt"
	"os"
	"strings"

	name "gitee.com/thubcc/blockchain/nameservice"
	"github.com/ethereum/go-ethereum/common"
)
// cmd arguments
var (
	argAddr   = flag.String("addr", "0x69B47aD51691905D4ae1B3b61B27164C1776D08B", "contract address")
	argAbi    = flag.String("abi", "contract/name.abi", "contract abi")
	argUrl    = flag.String("url", "http://localhost:8545", "ethereum rpc")
)
var (
	quitCommand = "~Q"
)
func main() {
	flag.Parse()
	config := &name.Config{
		*argUrl,
		*argAbi,
		common.HexToAddress("0xbfadc8b8497d4db8abf422abc7814a90e29f6e08"),
		common.HexToAddress(*argAddr),
		931,
	}
	service, err := config.NewNameService()
	if err != nil {
		fmt.Println("Initial service failure",err)
	}
	defer service.Close()
	var query  = make(chan common.Address,0)
	var result = make(chan map[common.Address]string,0)
	var quitMain = make(chan struct{},0)
	go service.Run(query,result)
	fmt.Println("test",service.Query(common.HexToAddress("0x931f0de91b692f3f505afae0d713bbc489727649"),true))
	go func(){		
		input := bufio.NewReader(os.Stdin)
		for {
			fmt.Print(fmt.Sprintf("input %s to quit>", quitCommand))
			txt, _ := input.ReadString('\n')
			txt = strings.TrimRight(txt, "\n\r")
			if txt == quitCommand {
				fmt.Println("Quit command received")
				service.Stop()
				close(quitMain)
				return
			}
			query <- common.HexToAddress(txt)
		}
	}()
	
	for {	
		select {
		case db := <-result:
			fmt.Println()
			for k,v := range db{
				fmt.Println(k.Hex(),v)
			}
			fmt.Print(fmt.Sprintf("input %s to quit>", quitCommand))
		case <-quitMain:
			fmt.Println("main Quit")
			return
		}
	}
}
